$reffile_dir = "/data4/bsi/RandD/Workflow/genotyping_1000genome_impute/complete1KGSNPS_split";
chomp($reffile_dir);
$reffile_dir =~ s/\/$//g;
$inputdir="./kk";
chomp($inputfile);

for($z=1;$z<24;$z++)
{
		print "dealing with chr $z\n";
		$inputfile = "$inputdir/$z/snps_chr$z.haps.gz";
		$outputfile="$inputdir/$z/snps_chr_temp_$z.haps.gz";
		chomp($outputfile);
		open(BUFF,"gunzip -c $inputfile |") or die "no file exists $inputfile\n";
		open(WRBUFF1,"|gzip  >$outputfile") or die "not able write to $outputfile\n";
		$prevchr = "";
		my %hash;
		undef(%check);
		while(<BUFF>)
		{
			#print "$.\n";
			chomp($_);
			@a = split(" ",$_);
			$flag = 0;
			if($z > 23)
			{
				$flag = 1;
			}
			if($prevchr ne $z && $z <24)
			{
				if($z == 23)
				{
					$tmp ="X";
				}
				else
				{
					$tmp=$z;
				}
				undef(%hash);
				$file1 = "$reffile_dir/chr".$tmp."_1K_impute_ref.txt";
				#die "$file1\n";
				open(INPUT1,$file1) or die "no file exists $file1\n";
				while($line = <INPUT1>)
				{
					chomp($line);
					@in = split("\t",$line);
					$hash{$in[0]} = $in[2];
				}
				$file2 = "$reffile_dir/chr".$tmp."_1K_nonimpute_ref.txt";
				open(INPUT1,$file2) or die "no file exists $file2\n";
				while($line = <INPUT1>)
						{
								chomp($line);
								@in = split("\t",$line);
								$hash{$in[0]} = $in[2];
						}
			}
			if(exists($hash{$a[1]}) && $flag != 1 )
			{
				$a[2] = $hash{$a[1]};
				$_ = join(" ",@a);
				if(!exists($check{"$z.$a[2]"}))
				{
					print WRBUFF1 "$_\n";	
					$check{"$z.$a[2]"}=1;
				}
			}
			$prevchr =$z;
		}
		system("mv $outputfile $inputfile");
}
